import { USER_INFO } from '@/const/storage'
import { provider, getEnv } from '@/const/index'

const baseUrl = 'https://uav-api.dev.sungmu.net'

const httpInterceptor = {
	invoke(options){
		
		if(!options.url.startsWith('http')) {
			options.url = baseUrl + options.url;
		}

		const userInfo = uni.getStorageSync(USER_INFO)
		const env = getEnv()
		const common = {
			source: provider[env.platform],
			siteUuid: '10bc3c83-4710-4c5a-be6d-9d12fc30111b'
		}
		//设置超时时间
		options.timeout = 10 * 1000
		options.data = {
		  common,
		  ...options.data || {}
		}
		options.header = {
			...options.header,
			token: userInfo?.token,
		}
	}
}

uni.addInterceptor('request',httpInterceptor)

export const http = (options) => {
	return new Promise(async (resolve,reject) => {
		uni.request({
			...options,
			success(res) {
				console.log(res);
				if ([404, 500, 502].includes(res.statusCode)) {
					uni.showToast({
						title: '服务器错误',
						icon: 'none',
					})
					reject(res)
				}

				if ([205].includes(res.data.code)) {
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
					})
					reject(res)
				}

				resolve(res.data)
			},
			fall(err){
				reject(err)
			},
		})
	})
}